#!/usr/bin/python
"""

archive_dnds_results.pl
    --new_results PATH
    --old_results PATH
    --archive_suffix SUFFIX

	copy old_results to new results, archiving old if MD5sum is different

"""

from optparse import OptionParser
import sys, os
import os.path
import re
import StringIO
import glob
import shutil

# add self to search path for testing
if __name__ == '__main__':
    exe_path = os.path.split(os.path.abspath(sys.argv[0]))[0]
    sys.path.append(os.path.abspath(os.path.join(exe_path,"..", "python_modules")))
    myname = os.path.split(sys.argv[0])[1]
    myname = os.path.splitext(myname)[0];
else:
    myname = __name__

import general_util
from custom_log import custom_log
from general_util import die_error




parser = OptionParser(version="%prog 1.0")
parser.add_option("-L", "--log_file_name", dest="logfile",
                  metavar="FILE", 
                  type="string",
                  help="name and path of log file")
parser.add_option("-n", "--new_results", dest = "new_results",
                  metavar="FILE", help="Full path of new results file")
parser.add_option("-o", "--old_results", dest = "old_results",
                  metavar="FILE", help="Full path of old results file to be overwritten")
parser.add_option("-s", "--suffix", dest="suffix",
				  type="string",
                  help="suffix to add to archived file.")
parser.add_option("-d", "--description", dest="description",
				  type="string",
                  help="description for log.")
parser.add_option("-q", "--quiet", dest = "quiet",
                  action="store_true", default=False,
                  help="Do not echo to shell but only print to log.")

parser.set_defaults(logfile = "") 
parser.set_defaults(old_results = None)
parser.set_defaults(new_results = None)
parser.set_defaults(suffix = "prev")
parser.set_defaults(description = "")

# get help string
f =StringIO.StringIO()
parser.print_help(f)
helpstr = f.getvalue()
(options, args) = parser.parse_args()

# mandatory options
if options.new_results == None:
    die_error("Please specify a file in --new_results.\n\n"+helpstr)
if options.old_results == None:
    die_error("Please specify a file in --old_results.\n\n"+helpstr)

status_log = custom_log(myname, options.logfile, options.quiet)
status_log.no_new_line_on_exit()


def get_command_output (command):
    child = os.popen(command)
    data = child.read()
    err = child.close()
    if err:
        die_error("%r failed with exit code %d" % (command, err))
    return data

#
#   make sure new result exists
# 
if not os.path.isfile(options.new_results):
    die_error("[%s] does not exist" % (options.new_results))

if not os.path.isfile(options.old_results):
    shutil.copy2(options.new_results, options.old_results)
    status_log.info(options.description + ": File saved, no previous versions to archive")
    sys.exit()

    
if not os.path.getsize(options.old_results):
    shutil.copy2(options.new_results, options.old_results)
    status_log.info(options.description + ": File saved, previous version was empty")
    sys.exit()

    
regex = re.compile(r"([a-fA-F0-9]{32})")
md5_new = get_command_output("md5sum " + options.new_results)
md5_old = get_command_output("md5sum " + options.old_results)
m_new = regex.search(md5_new)
if not m_new:
    die_error("md5sum failed for [" + options.new_results + "]")
m_old = regex.search(md5_old)
if not m_old:
    die_error("md5sum failed for [" + options.old_results + "]")
md5_new = m_new.group(1)
md5_old = m_old.group(1)

#
#   identical do not need to archive
# 
if md5_new == md5_old:
    status_log.info(options.description + ": File identical to previous version (not archived)")
    sys.exit()

#
#   get old files with suffix in old directory and add suffix
# 
old_path = os.path.split(options.old_results)[0]
if not os.path.isdir(old_path):
    die_error("%s is not a valid path" % (old_path))


files = glob.glob(os.path.join(old_path,  "*" + options.suffix))
for file in files:
    os.rename(file, file + options.suffix)


#
#   zip up the old file
# 
get_command_output("gzip " + options.old_results + "  -c1 > " + options.old_results + ".gz" + options.suffix)


#
#   copy to the new destinatin
# 

shutil.copy2(options.new_results, options.old_results)



status_log.info(options.description + ": File saved, previous versions archived")

    

